package com.thx.app.remote.util;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import mixedserver.protocol.RPCException;

import org.apache.commons.lang.StringUtils;

import com.thx.app.remote.UserLoginInter;
import com.thx.app.remote.model.RPCExceptionCode;
import com.thx.app.remote.model.RPCResponse;
import com.thx.app.remote.model.UserInfor_;
import com.thx.common.spring.BeanFactory;
import com.thx.common.util.AppContext;
import com.thx.common.util.PasswordUtil;
import com.thx.common.util.RandomTextUtil;
import com.thx.common.web.WebConstant;
import com.thx.file.util.WebFileUtil;
import com.thx.role.model.Role;
import com.thx.user.model.User;
import com.thx.user.service.UserManager;

public class UserLoginUtils {
	//SESSION存储的key
	public static String KEY_CAPTCHA_CODE = "key_captcha_code";
	/** 验证码长度默认4 */
	private static int length = 4;

	/**
	 * 登录
	 * @param username 用户名
	 * @param password 密码
	 * @param validator 验证码
	 * @param checkout 跟项目相关的登录验证接口
	 * @param saveattribute 保存跟项目相关的属性 接口
	 * @return 返回一个RPCLogin_对象 可以通过getAttribute 方法获得对象
	 * @throws RPCException
	 */
	public static RPCResponse login(HttpSession session,String username, String password) throws RPCException {
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User user = userManager.findByName(username);
		if (user == null) throw new RPCException("该用户不存在",RPCExceptionCode.SYSTEM_USER_NO_FOUND);
		//if (EncryptUtil.checkBybcrypt(password, user.getPassword())) {
		//modify Xuejw 2016-09-23 调整密码校验方式，支持多种加密方式
		if (PasswordUtil.isMatch(password, user.getPassword(), user.getSalt())) {
			RPCResponse response = UserLoginUtils.queryCurUserInfor(user);
			session.setAttribute(WebConstant.KEY_RPC_USER, user);
			return response;
		} else {
			throw new RPCException("密码输入错误", RPCExceptionCode.SYSTEM_USER_PWD_ERROR);
		}
	}
	
	/**
	 * 得到当前登录用户信息
	 */
	public static RPCResponse getCurUserInfor(HttpSession session) throws RPCException {
		UserLoginUtils.ValidateSession(session); //验证用户session是否有效 
		
		User user = (User)session.getAttribute(WebConstant.KEY_RPC_USER);
		return UserLoginUtils.queryCurUserInfor(user);
	}
	
	//返回内存中的用户信息
	public static RPCResponse queryCurUserInfor(User user) throws RPCException {
		RPCResponse response = new RPCResponse();
		response.setAttribute(UserLoginInter.SK_USERID, user.getUserId());
		response.setAttribute(UserLoginInter.SK_USERNAME, user.getUserName());
		response.setAttribute(UserLoginInter.SK_REALNAME, user.getRealName());
		response.setAttribute(UserLoginInter.SK_DEPID, user.getDepartment()==null?"":user.getDepartment().getDepId());
		response.setAttribute(UserLoginInter.SK_DEPNAME, user.getDepartment()==null?"":user.getDepartment().getDepName());
		response.setAttribute(UserLoginInter.SK_USERLOGO, user.getUserLogo()==null?"":user.getUserLogo());
		response.setAttribute(UserLoginInter.SK_MOBILE, user.getMobilePhone()==null?"":user.getMobilePhone());
		String roleStr="";
		if(user.getRoles()!=null){
		  for(Role role:user.getRoles()){
		    if(StringUtils.isNotBlank(roleStr)){
		      roleStr+=","+role.getRoleCode();
		    }else{
		      roleStr = role.getRoleCode();
		    }
		  }
		}
		response.setAttribute(UserLoginInter.SK_ROLES, roleStr);
		return response;
	}
	
    /**
     * 在用户登录成功后更新设备号
     * @param username
     * @param deviceId
     * @param imsi
     * @throws RPCException
     */
	public static boolean updateDeviceId(HttpServletRequest request,String userName, String deviceId, String imsi) throws RPCException {
		UserLoginUtils.ValidateSession(request.getSession()); //验证用户session是否有效 
		
		if(deviceId == null || deviceId.equals("")) {
			throw new RPCException("设备信息异常",RPCExceptionCode.SYSTEM_EXCEPTIONCODE);
		}
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User u = userManager.findByName(userName);
		if (u != null && (u.getDeviceId()==null || !u.getDeviceId().equals(deviceId))) {
			u.setDeviceId(deviceId);
			userManager.update(u);
			return true;
		}else{
			throw new RPCException("未匹配到该用户信息",RPCExceptionCode.SYSTEM_EXCEPTIONCODE);
		}
	}

	/**
	 * 获取验证码
	 * 
	 * @param deviceId
	 * @param simCardId
	 * @return
	 * @throws RPCException
	 */
	public static String getCaptcha(HttpSession session) throws RPCException {
		String[] key = RandomTextUtil.createRandomText(RandomTextUtil.Type.alphanumeric, length);
		session.setAttribute(KEY_CAPTCHA_CODE, key[0]);
		return key[1];
	}

	/**
	 * 修改密码
	 * @return
	 * @throws RPCException
	 */
	public static boolean updatePwd(HttpSession session,String userName, String oldPwd, String newPwd) throws RPCException {
		UserLoginUtils.ValidateSession(session); //验证用户session是否有效 
		
		User user = (User) session.getAttribute(WebConstant.KEY_RPC_USER);
		if(!userName.trim().equals(user.getUserName())) throw new RPCException("用户校验失败",RPCExceptionCode.SYSTEM_EXCEPTIONCODE);
			
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User olduser = userManager.findByName(userName);
		if (olduser == null) throw new RPCException("该用户不存在",RPCExceptionCode.SYSTEM_USER_NO_FOUND);
		//if (EncryptUtil.checkBybcrypt(oldPwd, olduser.getPassword())) {
        //modify Xuejw 2016-09-23 调整密码校验方式，支持多种加密方式;解决修改密码没有加密的问题
        if (PasswordUtil.isMatch(oldPwd, olduser.getPassword(), olduser.getSalt())) {
            // 加密密码
            String pwd = PasswordUtil.encrypt(newPwd, olduser.getSalt());
            // 更新加密类型
            String algorithmName = AppContext.getProperties(WebConstant.ENCRYPTED_TYPE);
			olduser.setPassword(pwd);
			olduser.setPwdFormat(algorithmName);
			userManager.save(olduser);
			return true;
		}else{
			throw new RPCException("用户名密码错误",RPCExceptionCode.SYSTEM_USER_PWD_ERROR);
		}
	}
	
	/**
	 * 注销操作
	 * @return
	 * @throws RPCException
	 */
	public static boolean logOut(HttpSession session) throws RPCException {
		session.setAttribute(WebConstant.KEY_RPC_USER, null);
		return true;
	}

	/**
	 * 保存用户信息
	 * 
	 * @param user
	 * @return
	 * @throws RPCException
	 */
	public static boolean saveUserInfor(HttpServletRequest request,UserInfor_ user) throws RPCException {
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User olduser = userManager.findByName(user.getUserName());
		if (olduser != null) throw new RPCException("用户已经存在",RPCExceptionCode.SYSTEM_NOTICE_USER);
		
		try {
			String device = (String)request.getAttribute(WebConstant.DEVICE);
			String deviceId = device.split("###")[2];
			String imei = device.split("###")[3];
			
			User u = new User();
			u.setComId("1");
			u.setUserName(user.getUserName());
			u.setPassword(user.getPassword());
			u.setCreateDate(new Date());
			u.setStatus(1 + "");
			u.setDeviceId(deviceId);
			u.setImsi(imei);
			u.setMobilePhone(user.getMobilePhone());
			userManager.save(u);
			return true;
		} catch (Exception e) {
			throw new RPCException("保存失败！",RPCExceptionCode.SYSTEM_EXCEPTIONCODE);
		}
	}
	
	/**
	 * 上传用户头像信息
	 */
	public static String sendUserImage(HttpSession session,byte[] picStream) throws RPCException {
		UserLoginUtils.ValidateSession(session); //验证用户session是否有效 
		
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User user = (User)session.getAttribute(WebConstant.KEY_RPC_USER);
		com.thx.file.model.File file = WebFileUtil.uploadAndSaveFile(user.getUserId()+".jpg", picStream);
		if(StringUtils.isNotBlank(file.getFileId())){
			User newUser = userManager.get(user.getUserId());
			newUser.setUserLogo(file.getFileId());
			userManager.save(newUser);
			return file.getFileId();
		}else{
			throw new RPCException("附件上传失败",RPCExceptionCode.SYSTEM_EXCEPTIONCODE);
		}
	}
	
	/**
	 * 用户注册用户名查询
	 * 到服务器端判断用户名是否已经注册
	 * parameter	用户名
	 */
	public static boolean loginUserSearch(String userName) throws RPCException {
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User user = userManager.findByName(userName);
		return user==null?false:true ;
	}
	
	/**
	 * 用户信息查询        [适用于已登录用户 查询其它用户信息]
	 * parameter	用户名
	 */
	public static RPCResponse queryUserSearch(HttpSession session,String userName) throws RPCException{
		UserLoginUtils.ValidateSession(session); //验证用户session是否有效 
		
		UserManager userManager = (UserManager) BeanFactory.getBean("userManager");
		User user = userManager.findByName(userName);
		return UserLoginUtils.queryCurUserInfor(user);
	}
	
	/**
	 * 验证用户session是否存在
	 * @param session
	 * @throws RPCException
	 */
	public static void ValidateSession(HttpSession session) throws RPCException {
		if (session.getAttribute(WebConstant.KEY_RPC_USER) == null) {
			throw new RPCException("未登录", RPCException.ERROR_CODE_INVALID_SESSION);
		}
	}
}
